/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package restauranteaplicacion.Ingresos;
import CapaNegocios.CNUsuarios;
import Clases.Observador;
import entidad.Empleados;
import entidad.Tipousuarios;
import java.awt.Component;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import restauranteaplicacion.MDI;
import CapaNegocios.CNEmpleados;
import CapaNegocios.CNTipoUsuarios;
import Clases.ComboBox;
import entidad.Usuarios;
import java.awt.Color;
import javax.swing.JOptionPane;

/**
 *
 * @author Milvia
 */
public class IngresoUsuario extends javax.swing.JInternalFrame implements Observer {

    /**
     * Creates new form IngresoUsuario
     */
    boolean formEmpleado; //variable si abrio el formulario empleado
    boolean formTipoUsuario; //Variable si abrio el formulario tipoUsuario.
     Observador obs; 
     Observador padre; 
     List<Empleados> listaEmpleado;
     List<Tipousuarios> listaTipoUsuario;
    public IngresoUsuario() {
        initComponents();
        formEmpleado=false;
        formTipoUsuario = false;
        obs = null;
        obs.addObserver(this);
        actualizarEmpleado();
        actualizarTipoUsuario();
        padre=null;
        usuarios1= null;
    }
    
    public IngresoUsuario(Observador observar) {
        initComponents();
        formEmpleado=false;
        formTipoUsuario = false;
        obs = null;
        actualizarEmpleado();
        actualizarTipoUsuario();
        padre=observar;
        usuarios1= null;
    }
    
    public IngresoUsuario(Observador observar, Usuarios us) {
        initComponents();
        formEmpleado=false;
        formTipoUsuario = false;
        obs = null;
        actualizarEmpleado();
        actualizarTipoUsuario();
        padre=observar;
        ingresarUsuario(us, usuarios1);
        if(usuarios1.getEmpleadoidEmpleado()!= null)
            cmbEmpleado.setSelectedItem(new ComboBox(usuarios1.getEmpleadoidEmpleado().getIdEmpleados(), 
                    usuarios1.getEmpleadoidEmpleado().getNombre()));
        if(usuarios1.getTipoUsuarioidTipoUsuario()!= null)
            cmbTipoUsuario.setSelectedItem(new ComboBox(usuarios1.getTipoUsuarioidTipoUsuario().getIdTipoUsuarios(),
                    usuarios1.getTipoUsuarioidTipoUsuario().getNombre()));
    }
    
    private void ingresarUsuario(Usuarios viejoPro, Usuarios usuarioNuevo )
    {
        usuarioNuevo.setActivo(viejoPro.getActivo());
        usuarioNuevo.setEmpleadoidEmpleado(viejoPro.getEmpleadoidEmpleado());
        usuarioNuevo.setIdUsuarios(viejoPro.getIdUsuarios());
        usuarioNuevo.setOrdenCollection(viejoPro.getOrdenCollection());
        usuarioNuevo.setPassword(viejoPro.getPassword());
        usuarioNuevo.setTipoUsuarioidTipoUsuario(viejoPro.getTipoUsuarioidTipoUsuario());
        usuarioNuevo.setUserName(viejoPro.getUserName());
        
    }
    
    private void actualizarTipoUsuario()
    {
        cmbTipoUsuario.removeAllItems();
        listaTipoUsuario = CNTipoUsuarios.buscarActivos();
        if(listaTipoUsuario!=null)
            for(Tipousuarios x : listaTipoUsuario)
                cmbTipoUsuario.addItem(new ComboBox(x.getIdTipoUsuarios(),x.getNombre()));
    }
    
    private void actualizarEmpleado()
    {
        cmbEmpleado.removeAllItems();
        listaEmpleado = CNEmpleados.buscarActivos();
        if(listaEmpleado!=null)
            for(Empleados x : listaEmpleado)
                cmbEmpleado.addItem(new ComboBox(x.getIdEmpleados(),x.getNombre()));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        usuarios1 = new entidad.Usuarios();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        cmbTipoUsuario = new javax.swing.JComboBox();
        btnCancelar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        cmbEmpleado = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setIconifiable(true);
        setTitle("Ingreso de Usuarios");
        setAutoscrolls(true);
        setPreferredSize(new java.awt.Dimension(666, 386));
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        jPanel1.setBackground(new java.awt.Color(54, 149, 240));
        jPanel1.setMaximumSize(new java.awt.Dimension(988, 50));
        jPanel1.setMinimumSize(new java.awt.Dimension(246, 50));
        jPanel1.setPreferredSize(new java.awt.Dimension(988, 50));

        jLabel4.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Creación de Usuarios");
        jPanel1.add(jLabel4);

        getContentPane().add(jPanel1);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setPreferredSize(new java.awt.Dimension(494, 500));

        jLabel1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel1.setText("Nombre Usuario");

        txtNombre.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        txtNombre.setNextFocusableComponent(txtPassword);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, usuarios1, org.jdesktop.beansbinding.ELProperty.create("${userName}"), txtNombre, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtNombre.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtNombreFocusGained(evt);
            }
        });
        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel2.setText("Contraseña");

        txtPassword.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        txtPassword.setNextFocusableComponent(cmbEmpleado);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, usuarios1, org.jdesktop.beansbinding.ELProperty.create("${password}"), txtPassword, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtPassword.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPasswordFocusGained(evt);
            }
        });

        jLabel14.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N

        jLabel15.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel15.setText("Empleado");

        jLabel16.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel16.setText("Tipo de Usuario");

        cmbTipoUsuario.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        cmbTipoUsuario.setNextFocusableComponent(btnGuardar);

        btnCancelar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/restauranteaplicacion/Ingresos/circle-x-3x.png"))); // NOI18N
        btnCancelar.setText("Salir");
        btnCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnGuardar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/circle-check-3x.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGuardar.setNextFocusableComponent(btnCancelar);
        btnGuardar.setPreferredSize(new java.awt.Dimension(89, 53));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        cmbEmpleado.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        cmbEmpleado.setNextFocusableComponent(cmbTipoUsuario);

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setForeground(new java.awt.Color(102, 102, 255));
        jButton1.setText("+");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setBackground(new java.awt.Color(255, 255, 255));
        jButton2.setForeground(new java.awt.Color(102, 102, 255));
        jButton2.setText("+");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel15)
                            .addComponent(jLabel16))
                        .addGap(127, 127, 127)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbEmpleado, 0, 219, Short.MAX_VALUE)
                            .addComponent(cmbTipoUsuario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(89, 89, 89)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPassword)
                            .addComponent(txtNombre)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(92, 92, 92))
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel14)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(cmbEmpleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(14, 14, 14)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel16)
                    .addComponent(cmbTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(58, 58, 58))
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap(295, Short.MAX_VALUE)
                    .addComponent(jLabel14)
                    .addContainerGap()))
        );

        getContentPane().add(jPanel2);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private boolean validar()
    {
        boolean val=true;
        if(txtNombre.getText().equals(""))
        {
            val=false;
            txtNombre.setBackground(Color.getHSBColor(255, 204, 204));
        }
        if(txtPassword.getText().equals(""))
        {
            val=false;
            txtPassword.setBackground(Color.getHSBColor(255, 204, 204));
        }
        return val;
    }
    
    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:  
        if(validar())
        {
            ComboBox h =(ComboBox)cmbEmpleado.getSelectedItem();
            int emp = h.getId();
            h =(ComboBox)cmbTipoUsuario.getSelectedItem();
            int tipo = h.getId();
            if(usuarios1 != null)
            {                
                Empleados em = CNEmpleados.buscarPorId(emp);
                Tipousuarios ti = CNTipoUsuarios.buscarPorId(tipo);
                usuarios1.setEmpleadoidEmpleado(em);
                usuarios1.setTipoUsuarioidTipoUsuario(ti);
                if(CNUsuarios.modificar(usuarios1))
                {
                    JOptionPane.showMessageDialog(this, "Se han Modificado el Usuario", 
                        "Exito", JOptionPane.INFORMATION_MESSAGE);
                    padre.actualizar();  
                    this.setVisible(false);
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "No se Modifico Correctamente  "
                            , "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            else if(CNUsuarios.insertar(txtNombre.getText(), txtPassword.getText(), tipo,emp))
            {
                JOptionPane.showMessageDialog(this, "Se han Agregado un Nuevo Usuario", 
                        "Exito", JOptionPane.INFORMATION_MESSAGE);
                if(padre!=null)
                    padre.actualizar();   
                this.setEnabled(false);
            }
            else
                JOptionPane.showMessageDialog(this, "Debe de llenar Todos los campos o verifique su conexcion a la Base "
                        + "de Datos", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(this, "Debe de llenar Todos los campos o verifique su conexcion a la Base de Datos", "Error", JOptionPane.ERROR_MESSAGE);
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        if(padre!=null)
            padre.actualizar();        
        this.setVisible(false);
        // TODO add your handling code here:
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        formTipoUsuario=true;
        obs= new Observador();
        obs.addObserver(this);
        IngresoTipoUsuario ing = new IngresoTipoUsuario(obs);
        MDI.getDesktopPane().add(ing);        
        this.Desactivar();
        ing.show();            
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        formEmpleado=true;
        obs= new Observador();
        obs.addObserver(this);
        IngresoEmpleado ing = new IngresoEmpleado(obs);
        MDI.getDesktopPane().add(ing);
        this.Desactivar();
        ing.show();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // TODO add your handling code here:
        char c=evt.getKeyChar();
          if(c ==' ') { 
              getToolkit().beep();                
              evt.consume(); 
          }
    }//GEN-LAST:event_txtNombreKeyTyped

    private void txtNombreFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNombreFocusGained
        // TODO add your handling code here:
        txtNombre.setBackground(Color.WHITE);
    }//GEN-LAST:event_txtNombreFocusGained

    private void txtPasswordFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasswordFocusGained
        // TODO add your handling code here:
        txtPassword.setBackground(Color.WHITE);
    }//GEN-LAST:event_txtPasswordFocusGained

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        // TODO add your handling code here:
        if(padre!=null)
            padre.actualizar(); 
    }//GEN-LAST:event_formInternalFrameClosing
    private void Desactivar()
    {
        for(Component x :this.jPanel2.getComponents())
        {
            x.setEnabled(false);
        }
    }
    private void Activar()
    {
        for(Component x :this.jPanel2.getComponents())
        {
            x.setEnabled(true);
        }
        txtNombre.setFocusable(true);
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbEmpleado;
    private javax.swing.JComboBox cmbTipoUsuario;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPassword;
    private entidad.Usuarios usuarios1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    @Override
    public void update(Observable o, Object arg) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        this.Activar();
        if(formEmpleado)
            actualizarEmpleado();
        if(formTipoUsuario)
            actualizarTipoUsuario();
        formEmpleado=false;
        formTipoUsuario=false;
        //txtNombre.setFocusable(true);
    }
}
